package com.safe.utils.timer;

import com.safe.exception.ParamErrorException;
import com.safe.service.TrajectoryService;
import com.safe.utils.BeanUtil;
import com.safe.utils.ConfigUtil;
import com.safe.utils.PositionUtil;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class InitDataThread extends Thread {
    ServerSocket serverSocket = null;
    Socket socket = null;
    int port = Integer.parseInt(ConfigUtil.getString("port"));
    String clientName = ConfigUtil.getString("client.name");
    ServerThread thread;
    TrajectoryService trajectoryService = (TrajectoryService) BeanUtil.getBean("trajectoryServiceImpl");

    @Override
    public void run() {
        // openTCPChannel(trajectoryService);
    }

    private void sendMessage() {
        Socket socket = null;
        OutputStream os = null;
        try {
            //服务器地址
            InetAddress serverIP = InetAddress.getByName("127.0.0.1");
            //创建socket连接
            socket = new Socket(serverIP, port);

            //发送消息IO流
            // os = socket.getOutputStream();
            // os.write("测试消息发送".getBytes());
            int i = 1;
            while (i > 0) {
                //发送消息IO流
                System.out.println(clientName + ",messageNum--" + i);
                os = socket.getOutputStream();
                os.write((clientName + ",messageNum--" + i).getBytes());

                Thread.sleep(1000);

                i++;
            }
        } catch (Exception e) {
            System.out.println("can't connect the tcp server......");
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void openTCPChannel(TrajectoryService trajectoryService) {
        System.out.println("start open TCP Channel......");

        try {
            //建立服务器socket
            serverSocket = new ServerSocket(port);

            //由于需要进行循环监听，因此获取消息的操作应放在一个while大循环中
            while (true) {
                try {
                    // 等待客户端连接
                    socket = serverSocket.accept();
                } catch (Exception e) {
                    System.out.println("tcp client connect error...");
                    e.printStackTrace();
                }

                thread = new ServerThread(socket, trajectoryService);
                thread.start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //服务端线程类
    //继承Thread类的话，必须重写run方法，在run方法中定义需要执行的任务。
    class ServerThread extends Thread {
        private Socket socket;
        InputStream inputStream;
        OutputStream outputStream;
        ByteArrayOutputStream byteArrayOutputStream;
        TrajectoryService trajectoryService;

        public ServerThread(Socket socket, TrajectoryService trajectoryService) {
            this.socket = socket;
            this.trajectoryService = trajectoryService;
        }

        public void run() {
            try {
                //接收客户端的消息并打印
                inputStream = socket.getInputStream();
                //管道流
                byteArrayOutputStream = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len;
                while ((len = inputStream.read(buffer)) != -1) {
                    byteArrayOutputStream.write(buffer, 0, len);
                    byteArrayOutputStream.flush();

                    System.out.println("客户端地址：" + socket.getInetAddress().getHostAddress());
                    System.out.println("客户端端口：" + socket.getPort());

                    PositionUtil.analysePosition(new String(buffer), trajectoryService);
                }

                //向客户端发送消息
                outputStream = socket.getOutputStream();
                outputStream.write("OK".getBytes());
                outputStream.flush();
                System.out.println("OK");
            } catch (ParamErrorException e) {
                System.out.println("train params error...");
            } catch (Exception e) {
                System.out.println("client close connect...");
                e.printStackTrace();
            } finally {
                try {
                    //操作结束，关闭socket
                    socket.close();
                } catch (IOException e) {
                    System.out.println("close connect error...");
                    e.printStackTrace();
                }
            }
        }
    }

    //服务端线程类
    //继承Thread类的话，必须重写run方法，在run方法中定义需要执行的任务。
    class PositionThread extends Thread {

        public void run() {
            try {
                // 将
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
